package net.ufrog.common.utils;

import net.ufrog.common.utils.Cryptos.HashType;

import java.util.UUID;

/**
 * 编码工具
 * 
 * @author ultrafrog
 * @version 1.0, 2012-10-26
 * @since 1.0
 */
public class Codecs {

    /** 构造函数 */
    public Codecs() {}

    /**
     * @return UUID
     */
    public static String uuid() {
        return UUID.randomUUID().toString();
    }

    /**
     * @param str 待转换字符串
     * @return 转换后字符串
     */
    public static String md5(String str) {
        return Cryptos.hashAndHex(str, HashType.MD5);
    }

    /**
     * @param str 待转换字符串
     * @return 转换后字符串
     */
    public static String ascii2Native(String str) {
        StringBuilder sb = Strings.builder();
        int begin = 0;
        int index = str.indexOf("\\u");

        while (index != -1) {
            sb.append(str.substring(begin, index));
            sb.append(ascii2Char(str.substring(index, index + 6)));
            begin = index + 6;
            index = str.indexOf("\\u", begin);
        }
        sb.append(str.substring(begin));
        return sb.toString();
    }

    /**
     * @param str 待转换字符串
     * @return 转换后字符
     */
    public static char ascii2Char(String str) {
        if (str.length() != 6) throw new IllegalArgumentException("Ascii string of a native character must be 6 character.");
        if (!"\\u".equals(str.substring(0, 2))) throw new IllegalArgumentException("Ascii string of a native character must start with \"\\u\".");

        String tmp = str.substring(2, 4);
        int code = Integer.parseInt(tmp, 16) << 8;
        tmp = str.substring(4, 6);
        code += Integer.parseInt(tmp, 16);
        return (char) code;
    }
}
